import { SESSION_CONFIG, SessionStatus } from '@/config/session';

// 会话管理类
export class SessionManager {
  private static instance: SessionManager;
  private checkInterval: NodeJS.Timeout | null = null;
  private onExpireCallback: (() => void) | null = null;
  private onWarningCallback: (() => void) | null = null;

  private constructor() {}

  static getInstance(): SessionManager {
    if (!SessionManager.instance) {
      SessionManager.instance = new SessionManager();
    }
    return SessionManager.instance;
  }

  // 设置登录时间
  setLoginTime(): void {
    const loginTime = Date.now();
    localStorage.setItem(SESSION_CONFIG.STORAGE_KEYS.LOGIN_TIME, loginTime.toString());
  }

  // 获取登录时间
  getLoginTime(): number {
    const loginTime = localStorage.getItem(SESSION_CONFIG.STORAGE_KEYS.LOGIN_TIME);
    return loginTime ? parseInt(loginTime) : 0;
  }

  // 设置会话超时时间（分钟）
  setTimeout(minutes: number): void {
    localStorage.setItem(SESSION_CONFIG.STORAGE_KEYS.SESSION_TIMEOUT, minutes.toString());
  }

  // 获取会话超时时间（分钟）
  getTimeout(): number {
    const timeout = localStorage.getItem(SESSION_CONFIG.STORAGE_KEYS.SESSION_TIMEOUT);
    return timeout ? parseInt(timeout) : SESSION_CONFIG.DEFAULT_TIMEOUT;
  }

  // 检查会话状态
  checkSessionStatus(): SessionStatus {
    const loginTime = this.getLoginTime();
    const timeout = this.getTimeout();
    const now = Date.now();
    const elapsedMinutes = (now - loginTime) / (1000 * 60);
    const warningTime = timeout - SESSION_CONFIG.WARNING_BEFORE;

    if (elapsedMinutes >= timeout) {
      return SessionStatus.EXPIRED;
    } else if (elapsedMinutes >= warningTime) {
      return SessionStatus.WARNING;
    } else {
      return SessionStatus.ACTIVE;
    }
  }

  // 获取剩余时间（分钟）
  getRemainingTime(): number {
    const loginTime = this.getLoginTime();
    const timeout = this.getTimeout();
    const now = Date.now();
    const elapsedMinutes = (now - loginTime) / (1000 * 60);
    return Math.max(0, timeout - elapsedMinutes);
  }

  // 开始会话监控
  startMonitoring(onExpire?: () => void, onWarning?: () => void): void {
    this.onExpireCallback = onExpire || null;
    this.onWarningCallback = onWarning || null;

    // 清除之前的定时器
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
    }

    // 设置新的定时器
    this.checkInterval = setInterval(() => {
      const status = this.checkSessionStatus();
      
      switch (status) {
        case SessionStatus.EXPIRED:
          this.handleSessionExpired();
          break;
        case SessionStatus.WARNING:
          this.handleSessionWarning();
          break;
      }
    }, SESSION_CONFIG.CHECK_INTERVAL);
  }

  // 停止会话监控
  stopMonitoring(): void {
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
      this.checkInterval = null;
    }
    this.onExpireCallback = null;
    this.onWarningCallback = null;
  }

  // 处理会话过期
  private handleSessionExpired(): void {
    this.stopMonitoring();
    this.clearSession();
    if (this.onExpireCallback) {
      this.onExpireCallback();
    }
  }

  // 处理会话警告
  private handleSessionWarning(): void {
    if (this.onWarningCallback) {
      this.onWarningCallback();
    }
  }

  // 清除会话数据
  clearSession(): void {
    localStorage.removeItem(SESSION_CONFIG.STORAGE_KEYS.LOGIN_TIME);
    localStorage.removeItem(SESSION_CONFIG.STORAGE_KEYS.USER_TOKEN);
  }

  // 刷新会话（延长登录时间）
  refreshSession(): void {
    this.setLoginTime();
  }

  // 检查是否已登录
  isLoggedIn(): boolean {
    const token = localStorage.getItem(SESSION_CONFIG.STORAGE_KEYS.USER_TOKEN);
    const loginTime = this.getLoginTime();
    return !!(token && loginTime);
  }
}

// 导出单例实例
export const sessionManager = SessionManager.getInstance(); 